document.write('<link rel="stylesheet" href="/cloud/oss/oss.css">');
accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000;

function send_request(serverUrl) {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp != null) {
        serverUrl = serverUrl
        xmlhttp.open("GET", serverUrl, false);
        xmlhttp.send(null);
        return xmlhttp.responseText
    } else {
        alert("Your browser does not support XMLHTTP.");
    }
};

function get_signature(serverUrl) {
    // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3) {
        body = send_request(serverUrl)
        var obj = eval("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}"
    } else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    } else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret, serverUrl) {
    if (ret == false) {
        ret = get_signature(serverUrl)
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'callback': callbackbody,
        'signature': signature,
        'x:origin_name':filename
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function go(config) {
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: config.browse_button,
        flash_swf_url:"/cloud/oss/plupload-2.1.2/js/Moxie.swf",//js中写死
        silverlight_xap_url:"/cloud/oss/plupload-2.1.2/js/Moxie.xap",//js中写死
        url: "http://oss.aliyuncs.com",
        file_data_name:config.hasOwnProperty("file_data_name")?config.file_data_name:"file",
        //单文件上传
        multi_selection:config.hasOwnProperty('multi_selection')?config.multi_selection:false,
        // multiple_queues : false,//不可多次上传
        filters: {
            mime_types: config.filters.mime_types,
            max_file_size: config.filters.max_size, //最大只能上传10mb的文件
            prevent_duplicates: config.filters.prevent_duplicates //不允许选取重复文件
        },

        init: {
            PostInit: function () {
                document.getElementById(config.postID).onclick = function () {
                    if(config.up_type==2){
                        set_upload_param(uploader, '', false, config.serverUrl);
                        return false;
                    }

                };
            },

            FilesAdded: function (up, files) {//文件添加支持提供
                plupload.each(files, function (file) {
                    document.getElementById(config.add_controller).innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'
                        + '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'
                        + '</div>';
                });
                if(config.up_type==1){
                    set_upload_param(uploader, '', false, config.serverUrl);
                    return false;
                }
            },

            BeforeUpload: function (up, file) {//上传前准备
                g_object_name_type = config.g_object_name_type
                set_upload_param(up, file.name, true, config.serverUrl);
            },

            UploadProgress: function (up, file) {//进度条
                var d = document.getElementById(file.id);
                d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                var prog = d.getElementsByTagName('div')[0];
                var progBar = prog.getElementsByTagName('div')[0]
                progBar.style.width = 2 * file.percent + 'px';
                progBar.setAttribute('aria-valuenow', file.percent);
            },

            FileUploaded: function (up, file, info) {//上传文件返回结果
                if (info.status == 200) {
                    document.getElementById(config.img).setAttribute("src",JSON.parse(info.response).url)
                    document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name) + ' 回调服务器返回的内容是:' + info.response;
                    config.success(up, file, info)
                } else {
                    console.log(info)
                    config.fail(up, file, info)
                }

            },
            Error: function (up, err) {//错误提示
                let msg="";
                if (err.code == -600) {
                    msg = "选择的文件太大了,可以根据应用情况，在upload.js 设置一下上传的最大大小"
                } else if (err.code == -601) {
                    msg="选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"
                } else if (err.code == -602) {
                    msg="这个文件已经上传过一遍了"
                } else {
                    msg = "Error xml:" + err.response;
                }
                alert(msg)
            }
        }
    });
    uploader.init();
}
